package com.bk.game.screen;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.OnActionCompleted;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.MoveBy;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.bk.game.cat.BoomBtn;
import com.bk.game.cat.CatActor;
import com.bk.game.cat.CatBtn;
import com.bk.game.global.BkGlobal;
import com.bk.game.global.GlobalContants;

/**
 * 描述:游戏主类
 * 
 * @author linqiang(866116)
 * @Since 2012-9-5
 */
public class GameScreen implements Screen, InputProcessor {

	// 舞台
	private Stage stage;

	private TextureAtlas bgta, btnta, boomta;

	private int startx, starty;

	private float step_x, step_y;

	private Rectangle fish;

	private BitmapFont scores;

	private BoomBtn boom;

	private Window dialog;
	private boolean hasDialog;
	private Button ok;

	// private Timer timer;
	private boolean changerTimer;
	private long timer;
	private boolean run;
	private boolean hasini;

	private Music music;
	private Sound sound;
	private Label label;

	public static int singlePressTime = 0;

	private InputMultiplexer multiplexer;

	// private class UpdateTask extends TimerTask {
	// @Override
	// public void run() {
	//
	// }// end run
	// }

	@Override
	public void dispose() {
		music.stop();
		sound.dispose();
		music.dispose();
		BkGlobal.actors.clear();
		scores.dispose();
		boomta.dispose();
		btnta.dispose();
		bgta.dispose();
		stage.dispose();
	}

	@Override
	public void hide() {
		BkGlobal.ISFINISHED = false;
		BkGlobal.NORMAL_TIME = 6f;
		BkGlobal.actors.clear();
		timer = 0;
		music.stop();
	}

	@Override
	public void pause() {
		// 保存时间差
		timer = System.currentTimeMillis() - timer;
		run = false;
		music.pause();
	}

	@Override
	public void render(float arg0) {
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
		stage.act(Gdx.graphics.getDeltaTime());
		stage.draw();
		label.x = 510 * BkGlobal.factorx - label.getPrefWidth();
		label.y = 245 * BkGlobal.factory;
		label.setText(BkGlobal.score + "");
		if (run && !BkGlobal.ISFINISHED) {
			if (System.currentTimeMillis() - timer >= 15000) {
				timer = System.currentTimeMillis();
				changerTimer = true;
				BkGlobal.NORMAL_TIME /= 1.5;
				for (CatActor cat : BkGlobal.actors) {
					cat.clearActions();
					if (cat.isDown()) {
						float f = Math.abs(cat.getStart() - cat.y);
						action(cat, BkGlobal.STEP_Y - f);
					} else {
						float f = Math.abs(cat.x - cat.getStart());
						action2(cat, BkGlobal.STEP_X - f);
					}
				}
				changerTimer = false;
			}
			if (BkGlobal.actors.size() == 0) {
				CatActor actor = new CatActor(0, startx, starty);
				action(actor, step_y);
				stage.addActor(actor);
				BkGlobal.actors.add(actor);
			} else {
				CatActor first = BkGlobal.actors.get(0);
				float x = first.x + 100 * BkGlobal.factorx;
				float y = 100 * BkGlobal.factory / 2 + first.y;
				if (fish.contains(x, y)) {
					BkGlobal.ISFINISHED = true;
					BkGlobal.NORMAL_TIME = 6f;
					for (CatActor cat : BkGlobal.actors) {
						cat.clearActions();
					}
					for (CatActor cat : BkGlobal.flyActors) {
						cat.clearActions();
					}
				} else {
					CatActor actor = BkGlobal.actors
							.get(BkGlobal.actors.size() - 1);
					if (actor.y <= Gdx.graphics.getHeight() - step_y) {
						CatActor actor1 = new CatActor(0, startx, starty);
						action(actor1, step_y);
						stage.addActor(actor1);
						BkGlobal.actors.add(actor1);
					}
				}// end if-else
			}// end if
		} else {
			if (!Gdx.input.isTouched()) {
				if (!hasDialog) {
					hasDialog = true;
					if (dialog == null) {
						TextureRegion txr = new TextureRegion(new Texture(
								Gdx.files.internal("gameover.png")));
						dialog = new Window("GAME OVER",
								new Window.WindowStyle(scores, new Color(),
										new NinePatch(txr)));
						dialog.width = 512 * BkGlobal.factorx;
						dialog.height = 128 * BkGlobal.factorx;
						// 为了让图片保持居中
						dialog.x = (Gdx.graphics.getWidth() - dialog.width) / 2;
						dialog.y = (Gdx.graphics.getHeight() - dialog.height)
								/ 2 + 100 * BkGlobal.factorx;
					}
					stage.addActor(dialog);
					if (ok == null) {
						ok = new Button(new TextureRegion(new Texture(
								Gdx.files.internal("ok.png")), 109, 59));
						ok.height = 100 * BkGlobal.factorx;
						ok.width = 200 * BkGlobal.factorx;
						ok.x = dialog.x + dialog.width - ok.width;
						ok.y = dialog.y - ok.height;
						// 给ok这个按钮添加监听器
						ok.setClickListener(new ClickListener() {
							@Override
							public void click(Actor arg0, float arg1, float arg2) {
								for (CatActor cat : BkGlobal.actors) {
									cat.remove();
								}
								for (CatActor cat : BkGlobal.flyActors) {
									cat.remove();
								}
								BkGlobal.currentGame.setScreen(new EndScreen());
							}
						});
					}
					stage.addActor(ok);
				}
			}
		}// end if
	}

	@Override
	public void resize(int arg0, int arg1) {

	}

	@Override
	public void resume() {
		// 还原时间差
		timer = System.currentTimeMillis() - timer;
		run = true;
		music.play();
	}

	@Override
	public void show() {
		timer = System.currentTimeMillis();
		Gdx.input.setCatchBackKey(true);
		hasDialog = false;
		if (!hasini) {
			// 初始化舞台
			stage = new Stage(Gdx.graphics.getWidth(),
					Gdx.graphics.getHeight(), true);
			fish = new Rectangle(500 * BkGlobal.factorx,
					340 * BkGlobal.factory, 115 * BkGlobal.factorx,
					95 * BkGlobal.factory);

			startx = (int) (BkGlobal.factorx * 35);
			starty = Gdx.graphics.getHeight();

			BkGlobal.getInstance().loadResource(BkGlobal.manager);
			bgta = BkGlobal.manager.get("bg.pack", TextureAtlas.class);
			TextureRegion region = bgta.findRegion("bg");
			Image bg = new Image(region);
			float scalex = (float) Gdx.graphics.getWidth()
					/ region.getRegionWidth();
			float scaley = (float) Gdx.graphics.getHeight()
					/ region.getRegionHeight();
			bg.scaleX = scalex;
			bg.scaleY = scaley;
			stage.addActor(bg);

			float left = GlobalContants.BTN_LEFT;
			boomta = BkGlobal.manager.get("boom.pack", TextureAtlas.class);
			boom = new BoomBtn(boomta.findRegion("boom"), left, 235);
			stage.addActor(boom);

			// 按钮
			btnta = BkGlobal.manager.get("btn.pack", TextureAtlas.class);
			CatBtn btn1 = new CatBtn("cat1", btnta.findRegion("btn1"), left,
					GlobalContants.BTN_TOP);
			stage.addActor(btn1);

			left += GlobalContants.BTN_LEFT_STEP;
			CatBtn btn3 = new CatBtn("cat3", btnta.findRegion("btn3"), left,
					GlobalContants.BTN_TOP);
			stage.addActor(btn3);

			left += GlobalContants.BTN_LEFT_STEP;
			CatBtn btn0 = new CatBtn("cat0", btnta.findRegion("btn0"), left,
					GlobalContants.BTN_TOP);
			stage.addActor(btn0);

			left += GlobalContants.BTN_LEFT_STEP;
			CatBtn btn2 = new CatBtn("cat2", btnta.findRegion("btn2"), left,
					GlobalContants.BTN_TOP);
			stage.addActor(btn2);

			step_x = scalex * 580;
			step_y = scaley * 120;

			BkGlobal.STEP_X = step_x - 100 * BkGlobal.factorx;
			BkGlobal.STEP_Y = step_y;

			scores = new BitmapFont(Gdx.files.internal("font.fnt"),
					Gdx.files.internal("font.png"), false);
			scores.setColor(Color.BLACK);
			scores.setScale(0.8f * BkGlobal.factory);
			label = new Label("0", new Label.LabelStyle(scores, Color.BLACK));
			stage.addActor(label);
			// stage.getSpriteBatch().begin();
			// scores.draw(stage.getSpriteBatch(), BkGlobal.score + "",
			// 350 * BkGlobal.factorx, 290 * BkGlobal.factory);
			// stage.getSpriteBatch().end();

			hasini = true;
			music = BkGlobal.manager.get("bgm.mp3", Music.class);
			music.setLooping(true);
			sound = BkGlobal.manager.get("fue.mp3", Sound.class);

			multiplexer = new InputMultiplexer();
			multiplexer.addProcessor(this);
			multiplexer.addProcessor(stage);
		}
		if (dialog != null) {
			dialog.remove();
		}
		if (ok != null) {
			ok.remove();
		}
		for (Actor a : stage.getActors()) {
			if (a instanceof CatBtn) {
				((CatBtn) a).reset();
			} else if (a instanceof CatActor) {
				a.remove();
			}
		}
		CatActor actor = new CatActor(0, startx, starty);
		action(actor, step_y);
		stage.addActor(actor);
		BkGlobal.actors.add(actor);
		run = true;
		boom.reset();
		BkGlobal.score = 0;
		singlePressTime = 0;

		label.x = 510 * BkGlobal.factorx - label.getPrefWidth();
		label.y = 245 * BkGlobal.factory;
		label.setText(BkGlobal.score + "");

		Gdx.input.setInputProcessor(multiplexer);
		// timer.schedule(new UpdateTask(), 3000, 3000);
		sound = BkGlobal.manager.get("fue.mp3", Sound.class);
		sound.play();
		music.play();
	}

	/**
	 * 描述:向下移动
	 * 
	 * @author linqiang(866116)
	 * @Since 2012-9-6
	 * @param actor
	 */
	private void action(final CatActor actor, float step) {
		float time = BkGlobal.NORMAL_TIME / 5 * step / BkGlobal.STEP_Y;
		MoveBy move = MoveBy.$(0, -step, time);
		move.setCompletionListener(new OnActionCompleted() {
			@Override
			public void completed(Action arg0) {
				if (!changerTimer)
					action2(actor, BkGlobal.STEP_X);
			}
		});
		actor.setDown(true);
		actor.action(move);
	}

	/**
	 * 描述:向左或者向右移动
	 * 
	 * @author linqiang(866116)
	 * @Since 2012-9-6
	 * @param actor
	 */
	private void action2(final CatActor actor, float step) {
		float time = BkGlobal.NORMAL_TIME * step / BkGlobal.STEP_X;
		float xBy = step;
		if (actor.isLeft()) {
			xBy = -xBy;
		}
		MoveBy move = MoveBy.$(xBy, 0, time);
		move.setCompletionListener(new OnActionCompleted() {
			@Override
			public void completed(Action arg0) {
				if (!changerTimer) {
					actor.change();
					action(actor, step_y);
				}
			}
		});
		actor.setDown(false);
		actor.action(move);
	}

	@Override
	public boolean keyDown(int arg0) {
		return false;
	}

	@Override
	public boolean keyTyped(char arg0) {
		return false;
	}

	@Override
	public boolean keyUp(int arg0) {
		if (arg0 == Input.Keys.BACK) {
			for (CatActor cat : BkGlobal.actors) {
				cat.clearActions();
				cat.remove();
			}
			for (CatActor cat : BkGlobal.flyActors) {
				cat.clearActions();
				cat.remove();
			}
			BkGlobal.currentGame.setScreen(BkGlobal.mainScreen);
		}
		return false;
	}

	@Override
	public boolean scrolled(int arg0) {
		return false;
	}

	@Override
	public boolean touchDown(int arg0, int arg1, int arg2, int arg3) {
		return false;
	}

	@Override
	public boolean touchDragged(int arg0, int arg1, int arg2) {
		return false;
	}

	@Override
	public boolean touchMoved(int arg0, int arg1) {
		return false;
	}

	@Override
	public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
		return false;
	}

	// @Override
	// public boolean touchDown(int arg0, int arg1, int arg2) {
	// return false;
	// }

}
